<template>
    <div class="product-form-container">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>{{ isEdit ? '编辑商品' : '添加商品' }}</span>
            <el-button @click="goBack">返回</el-button>
          </div>
        </template>
        
        <el-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-width="120px"
          :disabled="isViewMode"
        >
          <!-- 基本信息 -->
          <el-divider content-position="left">基本信息</el-divider>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商品名称" prop="name">
                <el-input v-model="formData.name" placeholder="请输入商品名称" />
              </el-form-item>
            </el-col>
            
            <el-col :span="12">
              <el-form-item label="商品分类" prop="category">
                <el-select v-model="formData.category" placeholder="请选择商品分类" style="width: 100%">
                  <el-option label="毛绒玩具" value="毛绒玩具" />
                  <el-option label="智能玩具" value="智能玩具" />
                  <el-option label="互动玩具" value="互动玩具" />
                  <el-option label="玩偶配件" value="玩偶配件" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商品价格" prop="price">
                <el-input-number
                  v-model="formData.price"
                  :precision="2"
                  :min="0"
                  :step="0.01"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            
            <el-col :span="12">
              <el-form-item label="商品库存" prop="stock">
                <el-input-number
                  v-model="formData.stock"
                  :min="0"
                  :step="1"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="商品状态" prop="is_hot">
                <el-radio-group v-model="formData.is_hot">
                  <el-radio :label="1">热门</el-radio>
                  <el-radio :label="0">普通</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          
          <!-- 商品图片 -->
          <el-divider content-position="left">商品图片</el-divider>
          
          <el-form-item label="主图" prop="image">
            <single-upload v-model="formData.image" />
          </el-form-item>
          
          <!-- 商品详情 -->
          <el-divider content-position="left">商品详情</el-divider>
          
          <el-form-item label="商品描述" prop="description">
            <el-input
              v-model="formData.description"
              type="textarea"
              :rows="4"
              placeholder="请输入商品描述"
            />
          </el-form-item>
          
          <el-form-item label="详细规格">
            <div v-for="(spec, index) in formData.specifications" :key="index" class="spec-item">
              <el-input v-model="spec.key" placeholder="规格名称" style="width: 200px;" />
              <span class="mx-2">:</span>
              <el-input v-model="spec.value" placeholder="规格值" style="width: 300px;" />
              
              <el-button 
                v-if="!isViewMode" 
                type="danger" 
                circle 
                @click="removeSpec(index)" 
                class="ml-2"
                :icon="Delete"
              />
            </div>
            
            <el-button 
              v-if="!isViewMode" 
              type="primary" 
              @click="addSpec" 
              :icon="Plus"
              class="mt-2"
            >
              添加规格
            </el-button>
          </el-form-item>
          
          <!-- 提交按钮 -->
          <el-form-item v-if="!isViewMode">
            <el-button type="primary" @click="submitForm" :loading="submitting">保存</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, computed, onMounted } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { ElMessage } from 'element-plus'
  import { Plus, Delete } from '@element-plus/icons-vue'
  import { getProductDetail, createProduct, updateProduct, uploadProductImage } from '../../api/product'
  import SingleUpload from '../../components/upload/SingleUpload.vue'
  
  const route = useRoute()
  const router = useRouter()
  const formRef = ref(null)
  
  // 是否为编辑模式
  const isEdit = computed(() => !!route.params.id)
  
  // 是否为查看模式
  const isViewMode = computed(() => route.query.view === 'true')
  
  const submitting = ref(false)
  
  // 上传请求头
  const uploadHeaders = computed(() => {
    return {
      Authorization: `Bearer ${localStorage.getItem('admin_token')}`
    }
  })
  
  // 表单数据
  const formData = reactive({
    name: '',
    category: '',
    price: 0,
    stock: 0,
    is_hot: 0,
    image: '',
    description: '',
    specifications: [{ key: '', value: '' }]
  })
  
  // 表单验证规则
  const rules = {
    name: [
      { required: true, message: '请输入商品名称', trigger: 'blur' },
      { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    category: [
      { required: true, message: '请选择商品分类', trigger: 'change' }
    ],
    price: [
      { required: true, message: '请输入商品价格', trigger: 'blur' }
    ],
    stock: [
      { required: true, message: '请输入商品库存', trigger: 'blur' }
    ],
    image: [
      { required: true, message: '请上传商品主图', trigger: 'change' }
    ],
    description: [
      { required: true, message: '请输入商品描述', trigger: 'blur' }
    ]
  }
  
  // 返回上一页
  const goBack = () => {
    router.back()
  }
  
  // 获取商品详情
  const fetchProductDetail = async (id) => {
    try {
      const data = await getProductDetail(id)
      // 只使用存在的字段
      formData.name = data.name || ''
      formData.description = data.description || ''
      formData.price = parseFloat(data.price) || 0
      formData.stock = data.stock || 0
      formData.category = data.category || ''
      formData.is_hot = data.is_hot || 0
      formData.image = data.image || ''
    } catch (error) {
      ElMessage.error('获取商品信息失败: ' + error.message)
    }
  }
  
  // 添加规格
  const addSpec = () => {
    formData.specifications.push({ key: '', value: '' })
  }
  
  // 移除规格
  const removeSpec = (index) => {
    formData.specifications.splice(index, 1)
  }
  
  // 提交表单
  const submitForm = () => {
    formRef.value.validate(async (valid) => {
      if (valid) {
        submitting.value = true
        
        try {
          // 准备提交的数据，只包含数据库表中存在的字段
          const submitData = {
            name: formData.name,
            description: formData.description,
            price: formData.price,
            category: formData.category,
            stock: formData.stock,
            is_hot: formData.is_hot,
            image: formData.image
          }
          
          if (isEdit.value) {
            await updateProduct(route.params.id, submitData)
            ElMessage.success('商品更新成功')
          } else {
            await createProduct(submitData)
            ElMessage.success('商品添加成功')
          }
          
          router.push('/products')
        } catch (error) {
          ElMessage.error('保存失败: ' + error.message)
        } finally {
          submitting.value = false
        }
      }
    })
  }
  
  // 重置表单
  const resetForm = () => {
    formRef.value.resetFields()
    
    if (isEdit.value) {
      // 如果是编辑模式，重新获取原始数据
      fetchProductDetail(route.params.id)
    } else {
      // 新增模式重置为初始状态
      formData.specifications = [{ key: '', value: '' }]
    }
  }
  
  onMounted(() => {
    if (isEdit.value) {
      fetchProductDetail(route.params.id)
    }
  })
  </script>
  
  <style scoped>
  .product-form-container {
    padding: 20px;
    background-color: #f0f2f5;
    min-height: calc(100vh - 60px);
  }
  
  .avatar-uploader {
    width: 178px;
    height: 178px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  
  .avatar-uploader:hover {
    border-color: #409EFF;
  }
  
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  
  .image-tip {
    color: #999;
    font-size: 12px;
    margin-top: 5px;
  }
  
  .spec-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }
  
  .mx-2 {
    margin: 0 5px;
  }
  
  .ml-2 {
    margin-left: 10px;
  }
  
  .mt-2 {
    margin-top: 10px;
  }
  
  .box-card {
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  </style>